package com.easyj.admin.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import com.easyj.base.common.export.ExpExcutor;
import com.easyj.base.common.export.ExpField;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.base.common.page.PageFilter;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.common.page.Page;
import com.easyj.admin.activiti.vo.SimpleApproveVO;
import com.easyj.admin.db.model.Training;
import com.easyj.admin.db.model.TrainingQO;
import com.easyj.admin.edu.service.TrainingService;
	/**
	* 学习交流
	*
	 */
	@RestController
	@RequestMapping(value = "/edu/training")
	public class TrainingController extends BaseController{

		@Autowired
		private  TrainingService trainingService;

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        Training entity = trainingService.findById(id);
	        return Result.Success(entity);
	    }
	    

		
		@RequestMapping(value = "findCommentsById", method = RequestMethod.GET)
		public Result findCommentsById(@RequestParam(value = "id") Long id) {
			return Result.Success(trainingService.findCommentsById(id));
			
		}
		
		/**
		* 新增申请
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('training','training:apply')")
		@PostMapping(value = "apply")
		public Result apply(@RequestBody @Validated Training entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
			trainingService.apply(entity);
			return Result.Success();
			
		}
		
		/**
		* 重新申请
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('training','training:apply')")
		@PostMapping(value = "reApply")
		public Result reApply(@RequestBody @Validated Training entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
			trainingService.reApply(entity);
			return Result.Success();
			
		}
		
		/**
		* 查询自己的申请
		* @param filter
		* @return
		 */

		@PostMapping(value = "findSelf")
		public Result findSelf(@RequestBody  TrainingQO filter) {
			
		    if(filter.getPage().getLimit()>MaxLimit) {
				return Result.Error(10009,"超出一次读取最大行数"); 
			}
		   //set applicantId
		    filter.setApplicantId(this.getUserId());
			Page<Training>  page =trainingService.findPage(filter);
			return Result.Success(page);
			
		}
		
		/**
		* 修改自己的申请
		 * @throws EasyjException 
		*/
		@PutMapping
		public Result update(@RequestBody @Validated Training entity,BindingResult validResult) throws EasyjException {
			
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			}  			
			trainingService.updateEntity(entity);
			return Result.Success();
			
		}

		
		
		 /**
 		    *取消自己的申请
		 * @throws EasyjException 
 		*/
		@RequestMapping(value = "cancel", method = RequestMethod.GET)
 		public Result cancel(@RequestParam(value = "id") Long id) throws EasyjException{
 			trainingService.cancel(id);
 			return Result.Success();
 			
 		}	


		
        /**
		  * 审批
         * @throws EasyjException 
		 */
		@PostMapping(value = "approve")
		public Result approve(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
			
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 
            entity.setApproveUserId(this.getUserId());
            
			trainingService.approve(entity);
			return Result.Success();
			
		}
		
		/**
		  * 审核
        * @throws EasyjException 
		 */
		@PostMapping(value = "auditApply")
		public Result auditApply(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
			
           if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 
           entity.setApproveUserId(this.getUserId());
           
			trainingService.auditApply(entity);
			return Result.Success();
			
		}
		
 		
 		/**
		* 分页查询
		* @param filter
		* @return
		 */
		@PreAuthorize("hasPermission('training','training:list')")
		@PostMapping(value = "findPage")
		public Result findPage(@RequestBody  TrainingQO filter) {			
		    if(filter.getPage().getLimit()>MaxLimit) {
				return Result.Error(10009,"超出一次读取最大行数"); 
			}
			Page<Training>  page =trainingService.findPage(filter);
			return Result.Success(page);
			
		}
		

      /**
		* 导出Excel
		* @param filter
		* @param expFields
		* @param response
		*/
		@PreAuthorize("hasPermission('training','training:list;training:approve')")
		@RequestMapping(value = "export", method = RequestMethod.POST)
		public void export(@RequestBody TrainingQO filter, HttpServletResponse response){
			try {
				 //导出的字段		
				List<ExpField> fields = new ArrayList<ExpField>();
				  fields.add(new ExpField("applyName","申请标题",""));
			      fields.add(new ExpField("applicantName","申请人",""));
			      fields.add(new ExpField("deptName","所属部门",""));
			      fields.add(new ExpField("applyTime","申请日期","","date"));
			      fields.add(new ExpField("name","学习交流名称",""));
			      fields.add(new ExpField("organization","组织单位",""));
			      fields.add(new ExpField("teacher","授课教师",""));
			      fields.add(new ExpField("startTime","开始时间","","date"));
			      fields.add(new ExpField("endTime","结束时间","","date"));
			      fields.add(new ExpField("period","学习课时",""));
			      fields.add(new ExpField("content","学习内容",""));
			      fields.add(new ExpField("address","培训地址",""));
			      fields.add(new ExpField("grade","学习成果、成绩",""));
			      fields.add(new ExpField("approveName","审批人",""));
			      fields.add(new ExpField("approveTime","审批日期","","date"));
			      fields.add(new ExpField("approveComment","审批意见",""));
			      fields.add(new ExpField("statusName","状态",""));
			    
				//生成 excel
				SXSSFWorkbook workbook=exportExcel(filter, fields);
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="学习交流"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			} catch (Exception ex) {
				log.error("TrainingController.export", ex);
			} 
		}
		
		/**
		* 导出excel,生成workbook 
		*/
		private SXSSFWorkbook exportExcel(final TrainingQO filter,List<ExpField> fields) {
			ExpExcutor<Training>  expExcutor=new ExpExcutor<Training>(){
				@Override
				protected Long getRecordCount() {
					return trainingService.count(filter);
				}

				@Override
				protected List<Training> getSheetData(int sheetSize, int sheetinx) {
					PageFilter queryPage=new PageFilter(sheetSize,sheetinx+1);
					filter.setPage(queryPage);
					List<Training> datas= trainingService.findList(filter);					
					return datas;
				}
			};
			SXSSFWorkbook workbook=expExcutor.export(fields,false);
			return workbook;
		}	
		
}

